import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  RadioButton,
  RadioGroup,
  Space
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { omit } from 'xe-utils'

import { cinemaApi, rechargeApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { optionsToMap } from '@/utils'

export default defineComponent({
  name: 'MovieManage',
  setup() {
    const { showConfirm } = useDialog()

    const curOptionItem = ref({} as any)
    const isSetSort = ref(false)
    const showDialog = ref(false)
    const dialogLoading = ref(false)

    const movieStatusOptions = [
      { label: '热映', value: 'HOT' },
      { label: '待映', value: 'WAIT' }
    ]

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        formConfig: {
          items: [
            {
              title: '电影名称',
              field: 'movieName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '影片类型',
              field: 'type',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: movieStatusOptions
              }
            },
            {
              title: '上映时间',
              field: 'startTime',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['publishStart', 'publishEnd']
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100
        },
        columns: [
          {
            title: 'ID',
            field: 'movieId'
          },
          {
            title: '影片名称',
            field: 'movieName'
          },
          {
            title: '想看人数号',
            field: 'likes'
          },
          {
            title: '评分',
            field: 'grade'
          },
          {
            title: '上映时间',
            field: 'publishDate',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss'],
            minWidth: 120
          },
          {
            title: '影片类型',
            field: 'publishStatus',
            formatter: ({ cellValue }) => {
              return optionsToMap(movieStatusOptions)[cellValue]
            }
          },
          {
            title: '排序',
            field: 'sort'
          },
          {
            title: '促销样式',
            field: 'label'
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 180
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              form = omit(form, ['startTime', 'endTime'])
              const data = await cinemaApi.getMovieList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },

                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    //设置排序
    function handleSortOrStyle(item, isSort) {
      curOptionItem.value.id = item.id
      isSetSort.value = isSort
      if (isSetSort.value) {
        curOptionItem.value.sort = item.sort
      } else {
        curOptionItem.value.label = item.label
      }
      showDialog.value = true
    }

    //确定
    async function dialogConfirm() {
      if (isSetSort.value && !curOptionItem.value.sort) {
        message.warn('请输入排序')
      }
      try {
        dialogLoading.value = true
        if (isSetSort.value) {
          await cinemaApi.setMovieSort(
            curOptionItem.value.id,
            curOptionItem.value.sort
          )
        } else {
          await cinemaApi.setMovieLabel(
            curOptionItem.value.id,
            curOptionItem.value.label
          )
        }
        showDialog.value = false
        refresh()
      } finally {
        dialogLoading.value = false
      }
    }

    //刷新
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }

    return {
      tableRef,
      tableConfig,
      isSetSort,
      showDialog,
      dialogLoading,
      curOptionItem,

      refresh,
      handleSortOrStyle,
      dialogConfirm
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleSortOrStyle(row, true)}
                >
                  设置排序
                </Button>

                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleSortOrStyle(row, false)}
                >
                  促销标签
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />

        <Modal
          v-model:visible={this.showDialog}
          width={600}
          confirmLoading={this.dialogLoading}
          title={this.isSetSort ? '设置排序' : '促销标签'}
          destroyOnClose
          onOk={this.dialogConfirm}
        >
          <Form labelCol={{ span: 4 }} style={{ marginTop: '15px' }}>
            <FormItem label={'排序'} required v-show={this.isSetSort}>
              <InputNumber
                placeholder={'请输入'}
                v-model:value={this.curOptionItem.sort}
                style={{ width: '300px' }}
                min={1}
                maxlength={5}
              />
              <p style={{ marginTop: '10px', color: '#888' }}>
                请输入大于等于1的整数，值越小排前面
              </p>
            </FormItem>

            <FormItem label={'促销标签'} v-show={!this.isSetSort}>
              <Input
                placeholder={'请输入'}
                v-model:value={this.curOptionItem.label}
                style={{ width: '300px' }}
                maxlength={8}
              />
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
